﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Lyon.Utility
{
    /// <summary>
    /// DES加密解密字符串
    /// </summary>
    public class DESTool
    {
        
        //默认密钥向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string Encrypt(string encryptString, string encryptKey)
        {
            Guard.ArgumentNotNullOrEmptyString(encryptString, "encryptString");
            Guard.ArgumentNotNullOrEmptyString(encryptKey, "encryptKey");
            if (encryptKey.Length < 8)
                throw new ArgumentException("加密密钥,要求为8位");

            byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            using (MemoryStream mStream = new MemoryStream())
            {
                CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(rgbKey, Keys), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string Decrypt(string decryptString, string decryptKey)
        {
            Guard.ArgumentNotNullOrEmptyString(decryptString, "decryptString");
            Guard.ArgumentNotNullOrEmptyString(decryptKey, "decryptKey");
            if (decryptKey.Length < 8)
                throw new ArgumentException("解密密钥,要求为8位,和加密密钥相同");

            byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
            byte[] inputByteArray = Convert.FromBase64String(decryptString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            using (MemoryStream stream = new MemoryStream())
            {
                CryptoStream cStream = new CryptoStream(stream, provider.CreateDecryptor(rgbKey, Keys), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        static readonly private string PrefixV2 = "LyonV2";
        /// <summary>
        /// 判断文件是否采用V2加密
        /// </summary>
        /// <param name="srcFileName"></param>
        /// <returns></returns>
        static public bool IsEncryptedV2(string srcFileName)
        {
            using (FileStream fsInput = new FileStream(srcFileName, FileMode.Open, FileAccess.Read))
            {
                byte[] fileFlag = ASCIIEncoding.ASCII.GetBytes(PrefixV2);
                fsInput.Read(fileFlag, 0, fileFlag.Length);
                return ASCIIEncoding.ASCII.GetString(fileFlag) == PrefixV2;
            }
        }
        /// <summary>
        /// 采用V2加密
        /// </summary>
        /// <param name="srcFileName"></param>
        /// <param name="destFileName"></param>
        static public void EncryptFileV2(string srcFileName, string destFileName)
        {
            using (FileStream fsInput = new FileStream(srcFileName, FileMode.Open, FileAccess.Read))
            {
                using (FileStream destStream = new FileStream(destFileName, FileMode.Create, FileAccess.Write))
                {
                    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                    ICryptoTransform encryptor = DES.CreateEncryptor();

                    byte[] fileFlag = ASCIIEncoding.ASCII.GetBytes(PrefixV2);
                    destStream.Write(fileFlag, 0, fileFlag.Length);
                    destStream.Write(DES.Key, 0, DES.Key.Length);
                    destStream.Write(DES.IV, 0, DES.IV.Length);

                    using (CryptoStream cryptostream = new CryptoStream(destStream, encryptor, CryptoStreamMode.Write))
                    {
                        WriteTo(fsInput, cryptostream);
                    }
                }
            }
        }
        /// <summary>
        /// 采用V2解密
        /// </summary>
        /// <param name="srcFileName"></param>
        /// <param name="destFileName"></param>
        static public void DecryptFileV2(string srcFileName, string destFileName)
        {
            using (FileStream fsInput = new FileStream(srcFileName, FileMode.Open, FileAccess.Read))
            {
                byte[] fileFlag = ASCIIEncoding.ASCII.GetBytes(PrefixV2);
                byte[] key = new byte[8];
                byte[] iv = new byte[8];
                fsInput.Read(fileFlag, 0, fileFlag.Length);
                fsInput.Read(key, 0, key.Length);
                fsInput.Read(iv, 0, iv.Length);

                using (FileStream destStream = new FileStream(destFileName, FileMode.Create, FileAccess.Write))
                {
                    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                    DES.Key = key;
                    DES.IV = iv;
                    ICryptoTransform decryptor = DES.CreateDecryptor();

                    using (CryptoStream cryptostream = new CryptoStream(destStream, decryptor, CryptoStreamMode.Write))
                    {
                        WriteTo(fsInput, cryptostream);
                    }
                }
            }
        }
        static void WriteTo(Stream readStream, Stream writeStream)
        {
            byte[] buffer = new byte[1024];
            int realCount = 0;
            do
            {
                realCount = readStream.Read(buffer, 0, buffer.Length);
                if (realCount > 0)
                    writeStream.Write(buffer, 0, realCount);
            }
            while (realCount == buffer.Length);
        }
    }
}
